import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Button, Text } from '@tarojs/components';
import { AtCurtain, AtRadio, AtTextarea, AtToast } from 'taro-ui';
import { useState, useEffect } from 'react';
import { getExamDtl, submitAnswer } from '@/api/application/interestAsw';
import "taro-ui/dist/style/components/textarea.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/toast.scss";
import "taro-ui/dist/style/components/curtain.scss";
import "taro-ui/dist/style/components/radio.scss";
import Header from '@/components/header';
import Return from '@/components/Return';
import css from './index.module.less';

export default function AswDetail() {
  const router = getCurrentInstance().router.params;
  const { examinationId, title, partyId } = router;

  //答题完成弹窗可见性
  const [finishVis, setFinishVis] = useState(false);
  //未完成题目弹窗可见性
  const [unfinishVis, setUnfinishVis] = useState(false);
  //答对题目的数量
  const [trueCount, setTrueCount] = useState(0);
  //未作答题目数量
  const [unfinishCount, setUnfinishCount] = useState(0);
  //用户选择题的答案
  const [answers, setAnswers] = useState([]);
  //题目相关信息
  const [questionInfo, setQuestionInfo] = useState({ founder: '', orgName: '', releaseTime: '', finishNumber: 0 });
  //题目数据
  const [questionList, setQuestionList] = useState([]);
  //加载中
  const [isOpened, setIsOpened] = useState(false);

  useEffect(() => {
    getExamDtl(examinationId).then((res) => {
      if (res.code === 200) {
        const { founder, orgName, releaseTime, finishNumber } = res.data;
        const defultValue = new Array(res.data.questionList.length).fill('', 0);
        setAnswers([...defultValue]);
        setQuestionList(res.data.questionList);
        setQuestionInfo({ founder, orgName, releaseTime, finishNumber });
      }
    });
  }, []);

  const choiceChange = (val, index) => {
    answers[index] = val;
    setAnswers([...answers]);
  };

  const fillChange = (val, index) => {
    answers[index] = val;
    setAnswers([...answers]);
  };

  const back = () => {
    setFinishVis(false);
    Taro.navigateBack();
  };

  const onFinish = () => {
    //答对题目数量, 未完成题目数量
    setIsOpened(true);
    let correctQuestionNumber = 0;
    let unfinishQuestionNumber = 0;
    questionList.forEach((item, index) => {
      if (answers[index] === '') unfinishQuestionNumber++;
      if (item.correctAnswer == item.choiceList[answers[index] - 1]) correctQuestionNumber++;
    });
    if (unfinishQuestionNumber > 0) {
      setUnfinishVis(true);
      setIsOpened(false);
      setUnfinishCount(unfinishQuestionNumber);
    }
    else {
      //答题所用时间
      const data = {
        answerDetailDtoList: [],
        correctQuestionNumber,
        examinationId,
        questionTotalNumber: questionList.length,
        userId: partyId
      };
      questionList.forEach((item, index) => {
        data.answerDetailDtoList.push(
          {
            answerContent: `${answers[index]}`,
            questionId: item.id
          });
      });
      setTrueCount(correctQuestionNumber);
      submitAnswer(data).then(res => {
        if (res.message === '提交成功') {
          setFinishVis(true);
        }
      }).finally(() => { setIsOpened(false); });
    }
  };

  return (
    <View className={css.home}>
      <Header message='在线答题' left='140px' />
      <Return />
      <View className={css.content}>
        <View className={css.problemInfo}>
          <View className={css.title}>
            {title}
          </View>
          <View className={css.info}>
            <View className={css.nameAndOrg}>
              {questionInfo.founder}&nbsp;&nbsp;&nbsp;{questionInfo.orgName}&nbsp;&nbsp;
            </View>
            <View className={css.timeAndBrowse}>
              <View className='at-icon at-icon-clock'>
                {questionInfo.releaseTime.slice(0, 10)}&nbsp;&nbsp;&nbsp;
                已完成:{questionInfo.finishNumber}
              </View>
            </View>
          </View>
        </View>

        <View className={css.divider}></View>

        <View className={css.problemList}>
          {
            questionList.map((item, questionIndex) => {
              const { id, questionType, question, choiceList } = item;
              const options = choiceList.map((choice, choiceIndex) => ({ label: choice, value: choiceIndex + 1 }));
              return (
                <View key={id}>

                  <View className={css.problem}>
                    {`${questionIndex + 1}. ${question}`}
                  </View>

                  <View>
                    {
                      questionType === 1 ?
                        <AtRadio
                          options={options}
                          value={answers[questionIndex]}
                          onClick={val => choiceChange(val, questionIndex)}
                        /> :
                        <AtTextarea
                          placeholder='请输入答案'
                          value={answers[questionIndex]}
                          onChange={val => fillChange(val, questionIndex)}
                        />
                    }
                  </View>
                </View>
              );
            })
          }
        </View>

        <View>
          <Button className={css.submitBtn} onClick={onFinish}>提交</Button>
        </View>
      </View>

      <AtCurtain isOpened={unfinishVis} onClose={() => { setUnfinishVis(false); }}>
        <View className={css.unfinish}>
          <View>
            您还有 <Text className={css.questionCount}>{unfinishCount}</Text> 道题目未作答
          </View>
          {/* <Button className={css.closeBtn} onClick={() => { setUnfinishVis(false); }}>
            确定
          </Button> */}
        </View>
      </AtCurtain>

      <AtCurtain isOpened={finishVis} onClose={back}>
        <View className={css.finish}>
          <View>恭喜你答对 <Text className={css.questionCount}>{trueCount}</Text> 题</View>
        </View>
        {/* <Button className={css.closeBtn} onClick={back}>
          确定
        </Button> */}
      </AtCurtain>

      <AtToast isOpened={isOpened} text='上传数据中...' status='loading' duration={0} hasMask />
    </View>
  );
}